package com.jmpt.fangbohui.ui.personalcenter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.AlreadyBBClientBean;
import com.jmpt.fangbohui.bean.ChangeHouseReadBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_area;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_city;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_lx;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_province;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_zone;
import com.jmpt.fangbohui.bean.EntryingHouseDropDownBean.Retval.date_zx;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.bean.ManagerHouseBean;
import com.jmpt.fangbohui.bean.ManagerHouseBean.ho_houseList;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.pic.PublishedActivity;
import com.jmpt.fangbohui.ui.base.BaseActivity;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.SharePerfencesUtils;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

public class EnterHouseActivity extends BaseHeadActivity implements
		OnItemSelectedListener {

	protected static final String TAG = "EnterHouseActivity";
	@ViewInject(R.id.sp_activity_entrying_house_infotype)
	private Spinner sp_activity_entrying_house_infotype;
	@ViewInject(R.id.sp_activity_entrying_house_housetype)
	private Spinner sp_activity_entrying_house_housetype;
	@ViewInject(R.id.et_activity_entrying_house_housenumber)
	private EditText et_activity_entrying_house_housenumber;
	@ViewInject(R.id.et_activity_entrying_house_housename)
	private EditText et_activity_entrying_house_housename;
	@ViewInject(R.id.et_activity_entrying_house_houseaddress)
	private EditText et_activity_entrying_house_houseaddress;
	@ViewInject(R.id.et_activity_entrying_house_housearea)
	private EditText et_activity_entrying_house_housearea;
	@ViewInject(R.id.et_activity_entrying_house_houseprice)
	private EditText et_activity_entrying_house_houseprice;
	@ViewInject(R.id.et_activity_entrying_house_subscription)
	private EditText et_activity_entrying_house_subscription;
	@ViewInject(R.id.bt_activity_entrying_house_submit)
	private Button bt_activity_entrying_house_submit;
	@ViewInject(R.id.sp_activity_entrying_house_province)
	private Spinner sp_activity_entrying_house_province;
	@ViewInject(R.id.sp_activity_entrying_house_city)
	private Spinner sp_activity_entrying_house_city;
	@ViewInject(R.id.sp_activity_entrying_house_zone)
	private Spinner sp_activity_entrying_house_zone;
	@ViewInject(R.id.sp_activity_entrying_house_area)
	private Spinner sp_activity_entrying_house_area;
	@ViewInject(R.id.sp_activity_entrying_house_decorate)
	private Spinner sp_activity_entrying_house_decorate;
	@ViewInject(R.id.et_activity_entrying_house_subscription2)
	private EditText et_activity_entrying_house_subscription2;
	@ViewInject(R.id.et_activity_entrying_house_rent)
	private EditText et_activity_entrying_house_rent;
	@ViewInject(R.id.sp_activity_entrying_house_roomcount)
	private Spinner sp_activity_entrying_house_roomcount;
	@ViewInject(R.id.sp_activity_entrying_house_hallcount)
	private Spinner sp_activity_entrying_house_hallcount;
	@ViewInject(R.id.et_activity_entrying_house_direction)
	private EditText et_activity_entrying_house_direction;
	@ViewInject(R.id.tv_activity_entrying_house_housearea)
	private TextView tv_activity_entrying_house_housearea;

	@ViewInject(R.id.ll_activity_entrying_house_subscription)
	private LinearLayout ll_activity_entrying_house_subscription;
	@ViewInject(R.id.ll_activity_entrying_house_subscription2)
	private LinearLayout ll_activity_entrying_house_subscription2;
	//租金
	@ViewInject(R.id.ll_activity_entrying_house_rent)
	private LinearLayout ll_activity_entrying_house_rent;
	//房源售价
	@ViewInject(R.id.ll_activity_entrying_house_houseprice)
	private LinearLayout ll_activity_entrying_house_houseprice;

	private SharedPreferences sp;
	private EntryingHouseDropDownBean dropDownBean;
	
	public static final int SUCCESS_UPLOADING = 222;
	public static final int FAILED_UPLOADING = 404;
	public static final int JUDGE_SUCCESS_SESSIONID = 500;
	public static final int JUDGE_FAILED_SESSIONID = 501;
	public static final int NETWORK_OBSTRUCT = 502;
	public static final int HOUSEID_SUCCESS = 503;
	public static final int HOUSEID_FAILED = 504;
	
	private ProgressDialog dialog;
	
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case SUCCESS_UPLOADING:
				dialog.dismiss();
//				ToastHelper.ShowToast("上传完成", getApplicationContext());
				
				Intent intent = new Intent(EnterHouseActivity.this,PublishedActivity.class);
				if(TextUtils.isEmpty(extraHouseID)){
					DebugLog.i((String)msg.obj);
					intent.putExtra("HouseID", (String)msg.obj);
				}else{
					intent.putExtra("HouseID", extraHouseID);
				}
				startActivity(intent);
				finish();
				break;
			case FAILED_UPLOADING:

				ToastHelper.ShowToast(msg.arg1, mContext);
				break;
			case JUDGE_SUCCESS_SESSIONID:
				hideLoading();
				break;
			case JUDGE_FAILED_SESSIONID:
				ToastHelper.ShowToast("用户未登录", EnterHouseActivity.this);
				Intent intent2 = new Intent(mContext,BrokerLoginActivity.class);
				startActivity(intent2);
				finish();
				break;
			case NETWORK_OBSTRUCT:
				ToastHelper.ShowToast(msg.arg1, mContext);
				break;
			case HOUSEID_SUCCESS:
				dataForView();
				break;
			case HOUSEID_FAILED:
				ToastHelper.ShowToast(houseIdData.msg, mContext);
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
		initView();
		initData();
		initEvent();
	}

	protected void dataForView() {
		String provinceID2 = houseIdData.retval.ho_house.ProvinceID;
		sp_activity_entrying_house_province.setSelection(provinceIds.indexOf(provinceID2));
		String areaID2 = houseIdData.retval.ho_house.AreaID;
		sp_activity_entrying_house_area.setSelection(areaIds.indexOf(areaID2));
		String cityID2 = houseIdData.retval.ho_house.CityID;
		sp_activity_entrying_house_city.setSelection(cityIds.indexOf(cityID2));
		String zoneID2 = houseIdData.retval.ho_house.ZoneID;
		sp_activity_entrying_house_zone.setSelection(zoneIds.indexOf(zoneID2));
		et_activity_entrying_house_direction.setText(houseIdData.retval.ho_house.H_CX);
		String zXID2 = houseIdData.retval.ho_house.ZXID;
		sp_activity_entrying_house_decorate.setSelection(zxIds.indexOf(zXID2));
		String lXID2 = houseIdData.retval.ho_house.LXID;
		sp_activity_entrying_house_housetype.setSelection(lxIds.indexOf(lXID2));
		String h_Hall = houseIdData.retval.ho_house.H_Hall;
		String h_Room = houseIdData.retval.ho_house.H_Room;
		sp_activity_entrying_house_hallcount.setSelection(Integer.parseInt(h_Hall)-1);
		sp_activity_entrying_house_roomcount.setSelection(Integer.parseInt(h_Room)-1);
		et_activity_entrying_house_rent.setText(houseIdData.retval.ho_house.H_RentPrice);
		et_activity_entrying_house_houseprice.setText(houseIdData.retval.ho_house.H_SalePrice);
		et_activity_entrying_house_housearea.setText(houseIdData.retval.ho_house.H_MJ);
		et_activity_entrying_house_houseaddress.setText(houseIdData.retval.ho_house.H_DZ);
		et_activity_entrying_house_housename.setText(houseIdData.retval.ho_house.H_Title);
		et_activity_entrying_house_housenumber.setText(houseIdData.retval.ho_house.H_Num);
		sp_activity_entrying_house_infotype.setSelection(Integer.parseInt(houseIdData.retval.ho_house.H_SaleOrRent)-1);
//		sp_activity_entrying_house_province.setSelection();
		if(houseIdData.retval.ho_house.H_SaleOrRent.equals("1")){
			et_activity_entrying_house_subscription.setText(houseIdData.retval.ho_house.H_payment);
		}else{
			et_activity_entrying_house_subscription2.setText(houseIdData.retval.ho_house.H_payment);
		}
	}
	
	private boolean isHouseManage = false;

	private void getExtra() {
		Intent intent = getIntent();
		extraHouseID = intent.getStringExtra("HouseID");
		if(!TextUtils.isEmpty(extraHouseID)){
			isHouseManage = true;
			obtainDataForNet(extraHouseID);
			
		}else{
			isHouseManage = false;
		}
	}

	private void obtainDataForNet(final String houseID) {

		LoginSQLiteOperator oper = new LoginSQLiteOperator(mContext);
		final List<String> querySessionId = oper.querySessionId();
		if(querySessionId.size() != 2){
			return;
		}
		
		new Thread(){
			public void run() {
				HttpClient httpClient = new DefaultHttpClient();
				try {
					
				    HttpGet postMethod = new HttpGet(Constants.URL.CHANGE_READ_ENTER_HOUSE+"?HouseID=" +houseID);
				    postMethod.setHeader("Cookie", "PHPSESSID=" + querySessionId.get(1)); 
				    HttpResponse response = httpClient.execute(postMethod); //执行GET方法
				    DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
				    
				    if(response.getStatusLine().getStatusCode() != 200){
				    	ToastHelper.ShowToast("网络不畅通，请稍后再试", mContext);
				    	return;
				    }
				    parsersHouseIdData(EntityUtils.toString(response.getEntity(), "utf-8"));
				    
								
				} catch (Exception e) {
				    e.printStackTrace();
				} 
			};
		}.start();
	}

	protected void parsersHouseIdData(String result) {
		DebugLog.i(result);
		Gson gson = new Gson();
		
		houseIdData = gson.fromJson(result, ChangeHouseReadBean.class);
		if(houseIdData == null)
			return;
		Message msg = Message.obtain();
		if(houseIdData.done.equals("true")){
			msg.what = HOUSEID_SUCCESS;
		}else{
			msg.what = HOUSEID_FAILED;
		}
		handler.sendMessage(msg);
	}

	private void init() {
		showLoading();
		isLogin();
	}
	/**
	 * 
	 * isLogin:是否经纪人登录中,是否有合法SessionID
	 *
	 * @author Lee
	 * @return
	 * @since JDK 1.7
	 */
	private void isLogin() {
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		querySessionId = oper.querySessionId();
		if(querySessionId.size() != 2){
			return;
		}
		showLoading();
		
		
		new Thread(){
			public void run() {
				HttpClient httpClient = new DefaultHttpClient();
				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
//					params.add(new BasicNameValuePair("AgentId",querySessionId.get(0)));
					
				    HttpPost postMethod = new HttpPost(Constants.URL.SecondaryHousingSubmittedURL);
				    postMethod.setHeader("Cookie", "PHPSESSID=" + querySessionId.get(1)); 
				    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
				    
								
				    HttpResponse response = httpClient.execute(postMethod); //执行POST方法
				    DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
				    
				    if(response.getStatusLine().getStatusCode() != 200){
				    	Message msg = Message.obtain();
					    msg.what = NETWORK_OBSTRUCT;
					    msg.obj = "网络暂不畅通，请稍后再试";
					    handler.sendMessage(msg);
				    	return;
				    }
				    parser(EntityUtils.toString(response.getEntity(), "utf-8"));
				    
								
				} catch (Exception e) {
				    e.printStackTrace();
				} 
			};
		}.start();
		
	}

	
	private void parser(String str){
		DebugLog.i("str" + str);
		Gson gson = new Gson();
		str = str.substring(str.indexOf("{"));
		HttpResult bean = gson.fromJson(str, HttpResult.class);
		Message msg = Message.obtain();
		//包含用户未登录的字段，则没有有效的seesionId信息 需要重新登录
		if(bean.msg.contains("未登录")){
		    msg.what = JUDGE_FAILED_SESSIONID;
		}else{
			msg.what = JUDGE_SUCCESS_SESSIONID;
		}
	    msg.obj = bean.msg;
	    handler.sendMessage(msg);
	}

	// 初始化数据，本地提取缓存下拉框，再到网上更新
	private void initData() {
		rooms = new String[] { "1", "2", "3", "4", "5", "6", "7", "8",
				"9", "10" };
		halls = new String[] { "1", "2", "3", "4", "5", "6", "7", "8",
				"9", "10" };
		// 赋值下拉框
		ArrayAdapter<String> roomAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, rooms);
		sp_activity_entrying_house_roomcount.setAdapter(roomAdapter);
		ArrayAdapter<String> hallAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, halls);
		sp_activity_entrying_house_hallcount.setAdapter(hallAdapter);

		sp = getSharedPreferences("config", MODE_PRIVATE);
		String cacheDropDown = sp.getString(
				Constants.SharedPreferences.CACHEDROPDOWN, null);
		if (TextUtils.isEmpty(cacheDropDown)) {
			Log.i(TAG, "cacheDropDown  != null");
			parsersAddress(cacheDropDown);
		}
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.GET, Constants.URL.SecondaryHousingDropDown,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Log.i(TAG, arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						sp.edit()
								.putString(
										Constants.SharedPreferences.CACHEDROPDOWN,
										arg0.result).commit();
						parsersAddress(arg0.result);
					}
				});
//		if(SharedPreferences.c)
		
	}

	protected void parsersAddress(String result) {
		Gson gson = new Gson();
		dropDownBean = gson.fromJson(result, EntryingHouseDropDownBean.class);
		// 拆分数据
		if (dropDownBean != null) {
			splitList(dropDownBean);
		}
	}

	private List<String> province;
	private List<String> city;
	private List<String> zone;
	private List<String> area;
	private List<String> lx;
	private List<String> zx;

	private List<String> provinceIds;
	private List<String> cityIds;
	private List<String> zoneIds;
	private List<String> areaIds;
	private List<String> lxIds;
	private List<String> zxIds;

	private String infoType;
	private String provinceId;
	private String cityId;
	private String zoneId;
	private String areaId;
	private String lxId;
	private String zxId;
	private int type;
	private String houseNumber;
	private String houseName;
	private String houseAddress;
	private String houseArea;
	private String housePrice;
	private String subscription;
	private String subscription2;
	private String rent;
	private String room;
	private String hall;
	private String cx;
	private List<String> querySessionId;
	private ChangeHouseReadBean houseIdData;
	private String[] rooms;
	private String[] halls;
	private String extraHouseID;
	private ArrayAdapter<String> provinceAdapter;
	private ArrayAdapter<String> cityAdapter;
	private ArrayAdapter<String> zoneAdapter;
	private ArrayAdapter<String> areaAdapter;

	private void splitList(EntryingHouseDropDownBean bean) {
		province = new ArrayList<String>();
		city = new ArrayList<String>();
		zone = new ArrayList<String>();
		area = new ArrayList<String>();
		lx = new ArrayList<String>();
		zx = new ArrayList<String>();

		provinceIds = new ArrayList<String>();
		cityIds = new ArrayList<String>();
		zoneIds = new ArrayList<String>();
		areaIds = new ArrayList<String>();
		lxIds = new ArrayList<String>();
		zxIds = new ArrayList<String>();

		Retval result = bean.retval;
		for (date_province date_provinces : result.date_province) {
			province.add(date_provinces.ProvinceName);
			provinceIds.add(date_provinces.ProvinceID);
		}
		for (date_city date_citys : result.date_city) {
			city.add(date_citys.CityName);
			cityIds.add(date_citys.CityID);
		}
		for (date_lx element : result.date_lx) {
			lx.add(element.LXName);
			lxIds.add(element.LXID);
		}
		for (date_zx element : result.date_zx) {
			zx.add(element.ZXName);
			zxIds.add(element.ZXID);
		}
		for (date_zone element : dropDownBean.retval.date_zone) {
			zone.add(element.ZoneName);
			zoneIds.add(element.ZoneID);
		}

		ArrayAdapter<String> zxAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, zx);
		sp_activity_entrying_house_decorate.setAdapter(zxAdapter);

		ArrayAdapter<String> lxAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, lx);
		sp_activity_entrying_house_housetype.setAdapter(lxAdapter);

		
		provinceAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, province);
		sp_activity_entrying_house_province.setAdapter(provinceAdapter);

		
		

		getExtra();
	}

	private void initView() {
		setContentView(R.layout.activity_entrying_house);
		ViewUtils.inject(this);
		showTitle("房源录入");
		showBackButton(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		ArrayAdapter<CharSequence> infoTypeAdapter = ArrayAdapter
				.createFromResource(this, R.array.infotype,
						android.R.layout.simple_spinner_dropdown_item);
		sp_activity_entrying_house_infotype.setAdapter(infoTypeAdapter);

	}

	private void initEvent() {
		bt_activity_entrying_house_submit
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						houseNumber = et_activity_entrying_house_housenumber
								.getText().toString().trim();
						houseName = et_activity_entrying_house_housename
								.getText().toString().trim();
						houseAddress = et_activity_entrying_house_houseaddress
								.getText().toString().trim();
						houseArea = et_activity_entrying_house_housearea
								.getText().toString().trim();
						housePrice = et_activity_entrying_house_houseprice
								.getText().toString().trim();
						subscription = et_activity_entrying_house_subscription
								.getText().toString().trim();
						subscription2 = et_activity_entrying_house_subscription2
								.getText().toString().trim();
						rent = et_activity_entrying_house_rent.getText()
								.toString().trim();
						if (infoType.equals("1")) {
							if (TextUtils.isEmpty(subscription)
									||TextUtils.isEmpty(housePrice)) {
								Toast.makeText(EnterHouseActivity.this,
										"*标志项不能为空", 1).show();
								return;
							}
						} else {
							if (TextUtils.isEmpty(subscription2)
									||TextUtils.isEmpty(rent)) {
								Toast.makeText(EnterHouseActivity.this,
										"*标志项不能为空", 1).show();
								return;
							}
						}
						if (TextUtils.isEmpty(houseNumber)
								|| TextUtils.isEmpty(houseName)
								|| TextUtils.isEmpty(houseAddress)
								|| TextUtils.isEmpty(houseArea)
						) {
							Toast.makeText(EnterHouseActivity.this, "*标志项不能为空",
									1).show();
							return;
						} else {
//							HttpUtils http = new HttpUtils();

							final List<NameValuePair> params = new ArrayList<NameValuePair>();
							params.add(new BasicNameValuePair("AgentId",querySessionId.get(0)));
//							RequestParams params = new RequestParams();
							// 出售类型
							
//							params.addBodyParameter("H_SaleOrRent", infoType);
							params.add(new BasicNameValuePair("H_SaleOrRent", infoType));
							// 类型id
//							params.addBodyParameter("LXID", lxId);
							params.add(new BasicNameValuePair("LXID", lxId));
							// 房源编号
//							params.addBodyParameter("H_Num", houseNumber);
							params.add(new BasicNameValuePair("H_Num", houseNumber));
							// 房源名称
//							params.addBodyParameter("H_Title", houseName);
							params.add(new BasicNameValuePair("H_Title", houseName));
							// 省份
//							params.addBodyParameter("ProvinceID", provinceId);
							params.add(new BasicNameValuePair("ProvinceID", provinceId));
							// 城市
//							params.addBodyParameter("CityID", cityId);
							params.add(new BasicNameValuePair("CityID", cityId));
							// 区域
//							params.addBodyParameter("ZoneID", zoneId);
							params.add(new BasicNameValuePair("ZoneID", zoneId));
							// 地段
//							params.addBodyParameter("AreaID", areaId);
							params.add(new BasicNameValuePair("AreaID", areaId));
							// 房源地址
//							params.addBodyParameter("H_DZ", houseAddress);
							params.add(new BasicNameValuePair("H_DZ", houseAddress));
							// 房源面积
//							params.addBodyParameter("H_MJ", houseArea);
							params.add(new BasicNameValuePair("H_MJ", houseArea));
							// 房源售价
//							params.addBodyParameter("H_SalePrice", housePrice);
							params.add(new BasicNameValuePair("H_SalePrice", housePrice));
							// 房源售价单价
							String unitPrice;
							if(infoType.equals("1")){
								unitPrice = String.valueOf((Long
										.valueOf(housePrice) / Long
										.valueOf(houseArea)));
							}else{
								unitPrice = "";
							}
//							params.addBodyParameter("H_SaleUnitPrice",unitPrice);
							params.add(new BasicNameValuePair("H_SaleUnitPrice",unitPrice));
							Log.i(TAG, " 单价" + unitPrice);
							if(isHouseManage){
								if(TextUtils.isEmpty(subscription)){
									params.add(new BasicNameValuePair("H_payment",subscription2));
								}else{
									params.add(new BasicNameValuePair("H_payment",subscription));
								}
							}else{
									
								// 售房订金
	//							params.addBodyParameter("H_paymentSale",subscription);
								params.add(new BasicNameValuePair("H_paymentSale",subscription));
								DebugLog.i(subscription);
								// 租房订金
	//							params.addBodyParameter("H_paymentRent",subscription2);
								params.add(new BasicNameValuePair("H_paymentRent",subscription2));
							}
							// 联系人
							//TODO
							LoginSQLiteOperator oper = new LoginSQLiteOperator(
									EnterHouseActivity.this);
							LoginBean bean = oper.query();
							String agentName = bean.getRetval().getAgentName();
							String userName = bean.getRetval().getUserName();

							String contact = TextUtils.isEmpty(agentName) ? userName
									: agentName;
//							params.addBodyParameter("H_SendInfoName", contact);
							params.add(new BasicNameValuePair("H_SendInfoName", contact));
							// 联系人电话
							SharedPreferences sp = EnterHouseActivity.this
									.getSharedPreferences(
											LoginActivity.FILE_NAME,
											Context.MODE_PRIVATE);

							String contact_phone = sp.getString("username", "");
//							params.addBodyParameter("H_SendInfoTel",contact_phone);
							params.add(new BasicNameValuePair("H_SendInfoTel",contact_phone));
							Log.i(TAG, "联系人" + contact);
							Log.i(TAG, "联系电话" + contact_phone);
							// 上传用户id
//							params.addBodyParameter("UserID", getUserId());
							params.add(new BasicNameValuePair("UserID", getUserId()));
							
							// 用户类型
//							params.addBodyParameter("UserType", type + "");
							params.add(new BasicNameValuePair("UserType", type + ""));
							// 新增字段
							// 租金
//							params.addBodyParameter("H_RentPrice",rent);
							params.add(new BasicNameValuePair("H_RentPrice",rent));
							room = String
									.valueOf(sp_activity_entrying_house_roomcount
											.getSelectedItem());
//							params.addBodyParameter("H_Room", room);
							params.add(new BasicNameValuePair("H_Room", room));
							hall = String
									.valueOf(sp_activity_entrying_house_hallcount
											.getSelectedItem());
//							params.addBodyParameter("H_Hall", hall);
							params.add(new BasicNameValuePair("H_Hall", hall));

							Log.i(TAG, room + " 大厅" + hall);
							// 装修情况
//							params.addBodyParameter("ZXID", zxId);
							params.add(new BasicNameValuePair("ZXID", zxId));
							// 略缩图
//							params.addBodyParameter("H_RentPrice", "");
							params.add(new BasicNameValuePair("H_RentPrice", ""));
							cx = et_activity_entrying_house_direction
									.getText().toString().trim();
//							params.addBodyParameter("H_CX",cx);
							params.add(new BasicNameValuePair("H_CX",cx));
							
							if(!TextUtils.isEmpty(extraHouseID)){
								params.add(new BasicNameValuePair("HouseID",extraHouseID));
							}
							dialog = new ProgressDialog(mContext);
							dialog.setCanceledOnTouchOutside(false);
							dialog.setTitle("正在提交");
							dialog.show();
							
							
							new Thread(){
								public void run() {
									HttpClient httpClient = new DefaultHttpClient();
									try {
										
										
									    HttpPost postMethod = null;
									    

										if(!TextUtils.isEmpty(extraHouseID)){
											DebugLog.i("不为空");
											postMethod = new HttpPost(Constants.URL.CHANGE_HOUSE_SAVE);
										}else{
											DebugLog.i("为空");
											postMethod = new HttpPost(Constants.URL.SecondaryHousingSubmittedURL);
										}
									    postMethod.setHeader("Cookie", "PHPSESSID=" + querySessionId.get(1)); 
									    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
									    
													
									    HttpResponse response = httpClient.execute(postMethod); //执行POST方法
									    DebugLog.i("resCode = " + response.getStatusLine().getStatusCode());
									    
									    if(response.getStatusLine().getStatusCode() != 200){
									    	Message msg = Message.obtain();
										    msg.what = NETWORK_OBSTRUCT;
										    msg.obj = "网络暂不畅通，请稍后再试";
										    handler.sendMessage(msg);
									    	return;
									    }
									    paserSubmitResult(EntityUtils.toString(response.getEntity(), "utf-8"));
									    
													
									} catch (Exception e) {
									    e.printStackTrace();
									} 
								};
							}.start();
							
						
						}

					}

				});
		// TODO 提交处理类型
		sp_activity_entrying_house_infotype.setOnItemSelectedListener(this);
		sp_activity_entrying_house_housetype.setOnItemSelectedListener(this);
		sp_activity_entrying_house_province.setOnItemSelectedListener(this);
		sp_activity_entrying_house_city.setOnItemSelectedListener(this);
		sp_activity_entrying_house_zone.setOnItemSelectedListener(this);
		sp_activity_entrying_house_area.setOnItemSelectedListener(this);
		sp_activity_entrying_house_decorate.setOnItemSelectedListener(this);

		// sp_activity_entrying_house_roomcount.setOnItemSelectedListener(this);
		// sp_activity_entrying_house_hallcount.setOnItemSelectedListener(this);
	}
	
	public void paserSubmitResult(String result){
		//{"done":"true","msg":"\u5f55\u5165\u6210\u529f","retval":{"flag":"Success","Reason":"\u53d1\u5e03\u6210\u529f","HouseID":296263}}


		DebugLog.i(result);
		Gson gson = new Gson();
		final HttpResult fromJson = gson
				.fromJson(result,
						HttpResult.class);
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				ToastHelper.ShowToast(
						fromJson.msg,
						EnterHouseActivity.this);
			}});

		if (fromJson.done
				.equals("true")) {
			//finish();
			Message msg = Message.obtain();
			msg.what = SUCCESS_UPLOADING;
			if(TextUtils.isEmpty(extraHouseID)){
				msg.obj = fromJson.retval.HouseID;
			}
			handler.sendMessage(msg);
		}else{
			Message msg = Message.obtain();
			msg.what = FAILED_UPLOADING;
			handler.sendMessage(msg);
		}
	}

	public class HttpResult {
		public String done;
		public String msg;
		public Retval retval;

		public class Retval {
			public String flag;
			public String Reason;
			public String HouseID;
		}
	}

	/*
	 * 获取当前用户id
	 */
	private String getUserId() {
		String id = "";
		LoginSQLiteOperator oper = new LoginSQLiteOperator(this);
		LoginBean query = oper.query();
		if (query.getRetval().getType() == 1) {
			// 普通用户
			id = query.getRetval().getUserId();
			type = 0;
		} else {
			// 经纪人
			id = query.getRetval().getAgentId();
			type = 1;
		}
		Log.i(TAG, "id" + id); 
		Log.i(TAG, "type" + type);
		return id;
	}

	// 确定被选择的有那个，下拉菜单联动的变更
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {

		if (sp_activity_entrying_house_infotype == parent) {
			infoType = String.valueOf(position + 1);
			Log.i(TAG, "信息类型 select");
			if (infoType.equals("1")) {
				// 出售
				ll_activity_entrying_house_subscription
						.setVisibility(View.VISIBLE);
				ll_activity_entrying_house_subscription2
						.setVisibility(View.GONE);
				et_activity_entrying_house_subscription2.setText("0");
				ll_activity_entrying_house_rent.setVisibility(View.GONE);
				et_activity_entrying_house_rent.setText("0");
				ll_activity_entrying_house_houseprice.setVisibility(View.VISIBLE);
			} else {
				// 出租
				ll_activity_entrying_house_subscription
						.setVisibility(View.GONE);
				ll_activity_entrying_house_subscription2
						.setVisibility(View.VISIBLE);
				et_activity_entrying_house_subscription.setText("0");
				ll_activity_entrying_house_rent.setVisibility(View.VISIBLE);
				ll_activity_entrying_house_houseprice.setVisibility(View.GONE);
				et_activity_entrying_house_houseprice.setText("0");
			}
		}
		if (sp_activity_entrying_house_housetype == parent) {
			lxId = lxIds.get(position);
			Log.i(TAG, "房源类型 select");
		}
		if (sp_activity_entrying_house_province == parent) {
			cityFilter(position);
		}
		if (sp_activity_entrying_house_city == parent) {
			zoneFilter(position);
		}
		if (sp_activity_entrying_house_zone == parent) {
			areaFilter(position);
		}
		if (sp_activity_entrying_house_area == parent) {
			areaId = areaIds.get(position);
			Log.i(TAG, "地段：select"+area.get(position));
		}
		if (sp_activity_entrying_house_decorate == parent) {
			zxId = zxIds.get(position);
			Log.i(TAG, "装修：select");
		}
	}
	private void cityFilter(int position) {
		if(provinceIds == null|| provinceIds.size() == 0)
			return;
		provinceId = provinceIds.get(position);
		Log.i(TAG, " 省份 select"+province.get(position));
		city.clear();
		cityIds.clear();
		for (date_city element : dropDownBean.retval.date_city) {
			if (element.ProvinceID.equals(provinceId)) {
				city.add(element.CityName);
				cityIds.add(element.CityID);
			}
		}
		if(cityAdapter == null){
			cityAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_dropdown_item, city);
			sp_activity_entrying_house_city.setAdapter(cityAdapter);
		}else{
			cityAdapter.notifyDataSetChanged();
		}
		sp_activity_entrying_house_city.setSelection(0);
		zoneFilter(0);
	}

	private void zoneFilter(int position) {
		if(cityIds == null|| cityIds.size() == 0)
			return;
		cityId = cityIds.get(position);
		Log.i(TAG, "城市 select"+city.get(position));
		zone.clear();
		zoneIds.clear();
		for (date_zone element : dropDownBean.retval.date_zone) {
			if (element.CityID.equals(cityId)) {
				zone.add(element.ZoneName);
				zoneIds.add(element.ZoneID);
			}
		}
		if(zoneAdapter == null){
			zoneAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_dropdown_item, zone);
			sp_activity_entrying_house_zone.setAdapter(zoneAdapter);
		}else{
			zoneAdapter.notifyDataSetChanged();
		}
		sp_activity_entrying_house_zone.setSelection(0);
		areaFilter(0);
	}


	private void areaFilter(int position){
		if(zoneIds == null|| zoneIds.size() == 0)
			return;
		zoneId = zoneIds.get(position);
		Log.i(TAG, "区域 select"+zone.get(position));
		area.clear();
		areaIds.clear();
		for (date_area element : dropDownBean.retval.date_area) {
			if (element.ZoneID.equals(zoneId)) {
				area.add(element.AreaName);
				areaIds.add(element.AreaID);
			}
		}
		if(areaAdapter == null){
			areaAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_dropdown_item, area);
			sp_activity_entrying_house_area.setAdapter(areaAdapter);
		}else{
			areaAdapter.notifyDataSetChanged();
		}
		sp_activity_entrying_house_area.setSelection(0);
		if(areaIds == null || areaIds.size() == 0)
			return;
		areaId = areaIds.get(0);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

}
